document.addEventListener('DOMContentLoaded', function () {
  app.initPage();
});

function loadPage() {
  setTimeout(() => {
    isTeaLogin();
  }, 200);
  loadTeacherForm();
  $.get(`${app.urlLocation.queryAllTeacher}/${app.pageHelper.global_page}/${app.pageHelper.global_limit}`, res => {
    if (res.data.length === 0 && app.pageHelper.global_page > 1) {
      app.pageHelper.global_page--;
      loadPage();
    } else {
      loadTeacherTable(res);
      loadTeacherPage(res);
    }
  })
}

function loadTeacherTable(teachers) {
  layui.use(['table', 'layer'], () => {
    let table = layui.table,
        layer = layui.layer;
    table.render({
      elem: '#teacher',
      data: teachers.data,
      limit: app.pageHelper.global_limit,
      toolbar: '#teacher-toolbar',
      cols: [
        [
          {type: 'checkbox'},
          {field: 'teacherNo', title: '职工号'},
          {field: 'name', title: '教师姓名'},
          {
            field: 'gender', title: '性别', templet: d => {
              return d.gender === 0 ? '男' : '女';
            }
          },
          {field: 'clazz', title: '教授科目'},
          {field: 'phone', title: '联系电话'},
          {field: 'email', title: '邮箱'},
          {
            field: 'createdTime', title: '信息录入时间', templet: d => {
              return app.formatDate(new Date(d.createdTime));
            }
          },
          {title: '操作', toolbar: '#teacher-tool'}
        ]
      ]
    });
    table.on('toolbar(teacher)', obj => {
      switch (obj.event) {
        case 'add':
          $('.layout .layout-title').text('录入教师信息');
          $('.layout button:eq(0)').text('添加').attr('lay-filter', 'add');
          getClazzList();
          showLayout($('.layout'));
          break;
        case 'del':
          layer.confirm('删除将不可恢复，是否删除?', {
            btn: ['删除', '不删除']
          }, () => {
            let data = table.checkStatus(obj.config.id).data,
                ids = [];
            $.each(data, (i, v) => {
              ids[i] = v.id;
            });
            ids = JSON.stringify(ids);
            ids = ids.substring(2, ids.length - 2);
            $.post(`${app.urlLocation.deleteTeacher}`, {id: ids}, res => {
              if (res === 200)
                layer.msg('教师信息删除成功');
              else
                layer.msg('教师信息删除失败，请重试或联系系统管理员');
            })
          });
          break;
      }
    });
    table.on('tool(teacher)', obj => {
      let event = obj.event,
          data = obj.data;
      switch (event) {
        case 'edit':
          $('.layout .layout-title').text('修改教师信息');
          $('.layout button:eq(0)').text('修改').attr('lay-filter', 'edit');
          $.get(`${app.urlLocation.queryTeacherById}/${data.id}`, teacher => {
            $('.layout input[name=id]').val(teacher.id);
            $('.layout input[name=teacherNo]').val(teacher.teacherNo);
            $('.layout input[name=name]').val(teacher.name);
            $('.layout input[name=age]').val(teacher.age);
            $('.layout select[name=gender] option').eq(teacher.gender).attr('selected', 'selected');
            $('.layout select[name=isAdmin] option').eq(teacher.isAdmin).attr('selected', 'selected');
            $.get(`${app.urlLocation.queryAllCt}`, cts => {
              let ctsHtml = '';
              $.each(cts, (i, v) => {
                if (teacher.clazz === v.id)
                  ctsHtml += `<option value="${v.id}" selected="selected">${v.classType}</option>`;
                else
                  ctsHtml += `<option value="${v.id}">${v.classType}</option>`;
                $('.layout select[name=clazz]').html(ctsHtml);
                app.resetForm();
              });
            });
            $('.layout input[name=phone]').val(teacher.phone);
            $('.layout input[name=email]').val(teacher.email);
          });
          showLayout($('.layout'));
          break;
        case 'del':
          layer.confirm('删除将不可恢复，是否删除?', {
            btn: ['删除', '不删除']
          }, () => {
            $.post(`${app.urlLocation.deleteTeacher}`, {id: data.id}, res => {
              if (res === 200)
                layer.msg('教师信息删除成功');
              else
                layer.msg('教师信息删除失败，请重试或联系系统管理员');
              loadPage();
            })
          });
          break;
      }
    })
  })
}

function loadTeacherPage(teachers) {
  layui.use('laypage', () => {
    layui.laypage.render({
      elem: 'teacher-page',
      curr: app.pageHelper.global_page,
      count: teachers.count,
      limit: app.pageHelper.global_limit,
      limits: [10, 20, 30, 40, 50],
      layout: ['count', 'prev', 'page', 'next', 'limit'],
      jump: function (obj, first) {
        if (!first) {
          app.pageHelper.global_page = obj.curr;
          app.pageHelper.global_limit = obj.limit;
          loadPage();
        }
      }
    })
  })
}

function loadTeacherForm() {
  layui.use(['element', 'form', 'layer'], () => {
    let form = layui.form,
        layer = layui.layer;
    form.on('submit(add)', obj => {
      let field = obj.field;
      $.get(`${app.urlLocation.queryTeaByNo}`, {teacherNo: field.teacherNo}, result => {
        if (result === '') {
          $.post(`${app.urlLocation.addTeacher}`, field, res => {
            if (res === 200)
              layer.msg('教师信息添加成功');
            else
              layer.msg('教师信息添加失败，请重试或联系系统管理员');
            hideLayout($('.layout'));
            loadPage();
          });
        } else {
          layer.msg('该教师信息已存在，请勿重复添加');
        }
      })
    });
    form.on('submit(edit)', obj => {
      let field = obj.field;
      $.post(`${app.urlLocation.updateTeacher}`, field, res => {
        if (res === 200)
          layer.msg('教师信息修改成功');
        else
          layer.msg('教师信息修改失败，请重试或联系系统管理员');
        hideLayout($('.layout'));
        loadPage();
      })
    });
  })
}

function getClazzList() {
  $.get(`${app.urlLocation.queryAllCt}`, res => {
    let optionHtml = '';
    $.each(res, (i, v) => {
      optionHtml += `<option value="${v.id}">${v.classType}</option>`;
    });
    $('.layout select[name=clazz]').html(optionHtml);
    app.resetForm();
  })
}

$('.layout input[name=age]').keyup(function () {
  let reg = /[\u4E00-\u9FA5\uF900-\uFA2D]/;
  if (reg.test(this.value)) {
    this.value = '';
  } else {
    if (!this.value.match(/^\d*?$/))
      this.value = this.value.substring(0, this.value.length - 1);
  }
});